<template>
  <!-- auto-width用于处理table内嵌选择框下拉框无法自适应 -->
  <el-select
    ref="select"
    v-model="data"
    filterable
    remote
    :clearable="clearable"
    :placeholder="placeholder"
    :remote-show-suffix="remoteShowSuffix"
    :remote-method="hanlderselect"
    :loading="state.loading"
    :disabled="disabled"
    @change="handleChange"
    :auto-width="autoWidth"
    :fit-input-width="fillInputWidth"
  >
    <el-option
      v-for="item in state.options"
      :key="item.id"
      :label="item.label"
      :value="item.value"
      @click="handleOptionClick(item)"
    >
      <span v-if="!labelSpaceBetween">{{ item.selectLabel }}</span>
      <span style="float: left" v-if="labelSpaceBetween">{{
        item.leftName
      }}</span>
      <span style="float: right" v-if="labelSpaceBetween">{{
        item.rigthName
      }}</span>
    </el-option>
  </el-select>
</template>

<script setup>
import {
  reactive,
  ref,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  computed,
  watch
} from 'vue'
import request from '@/public/request'
import { ElMessage } from 'element-plus'

// 父组件传递的属性
const props = defineProps({
  modelData: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  },
  urlType: {
    type: String,
    default: ''
  },
  urlQueryData: {
    type: String,
    default: ''
  },
  //初始化option
  option: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  labelSpaceBetween: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  fillInputWidth: {
    type: Boolean,
    default: true
  },
  autoWidth: {
    type: Boolean,
    default: false
  },
  indexOfBox: {
    type: Number,
    default: -1
  },
  // 是否需要港口的value为code
  needPortCode: {
    type: Boolean,
    default: false
  },
  remoteShowSuffix: {
    type: Boolean,
    default: true
  }
})
// 计算数据生成data
const data = computed({
  get: () => {
    return props.modelData
  },
  set: (value) => {
    emit('update:modelData', value)
  }
})
// 父组件触发条件
const emit = defineEmits(['getOption', 'handleChange', 'update:modelData'])

const state = reactive({
  options: props.option,
  loading: false,
  ALLURL: {
    //货物来源
    basedictdetail: '/api/basedictdetail/querypage',
    //船代
    crcontactcompany: '/api/crcontactcompany/query',
    //港口API
    port: '/api/csport/querypage',
    //船名（船舶信息）API
    CsShip: '/api/csship/querypage',
    // 航次
    CsVoyage: '/api/csvoyage/querypage',
    // 挂港信息
    CsVoyagePort: '/api/csvoyageport/querypage',
    //包装单位API()
    CsPackageType: '/api/cspackagetype/querypage',
    //箱型箱尺
    csContainer: '/api/cscontainer/querypage',
    //船司信息
    CsShipCompany: '/api/csshipcompany/querypage',
    //海运航线
    tradelane: '/api/csportroute/querypage'
  }
})
defineExpose({})
//选择对应的item
const hanlderselect = (queryName) => {
  console.log(queryName, 'queryName')
  if (!state.ALLURL[props.urlType]) {
    throw new Error('urlType不存在')
  }
  state.loading = true
  request
    .get(state.ALLURL[props.urlType], getQueryData(queryName))
    .then((res) => {
      if (props.urlType == 'basedictdetail') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.label,
            label: item.label,
            selectLabel: item.label,
            leftName: item.label,
            rigthName: item.label
          }
        })
      } else if (props.urlType == 'crcontactcompany') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.comNameCn,
            label: item.comNameCn,
            selectLabel: `${item.comCode} | ${item.comNameCn}`,
            leftName: item.comNameCn,
            rigthName: item.comCode
          }
        })
      } else if (props.urlType == 'port') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: props.needPortCode ? item.portCode : item.nameEn,
            label: `${item.portCode} | ${item.nameEn}`,
            selectLabel: `${item.portCode} | ${item.nameEn}`,
            rigthName: item.portCode
          }
        })
      } else if (props.urlType == 'CsPackageType') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.typeNameEn,
            label: item.typeNameEn,
            selectLabel: item.typeNameEn
          }
        })
      } else if (props.urlType == 'CsShip') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.nameEn,
            label: item.nameEn,
            selectLabel: item.nameEn
          }
        })
      } else if (props.urlType == 'CsVoyage') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.voyageName,
            label: item.voyageName,
            selectLabel: item.voyageName
          }
        })
      } else if (props.urlType == 'tradelane') {
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.nameCh,
            label: item.nameCh,
            selectLabel: item.nameCh
          }
        })
      } else if (props.urlType == 'csContainer') {
        // 箱型箱量
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.containerCode,
            label: item.containerCode,
            teu: item.teu,
            selectLabel: item.containerCode
          }
        })
      } else if (props.urlType == 'CsShipCompany') {
        // 船司信息
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.companyCode,
            label: item.companyCode,
            leftName: item.companyCode,
            rigthName: item.shortNameCh,
            selectLabel: `${item.companyCode}|${item.shortNameCh}`
          }
        })
      } else if (props.urlType == 'CsVoyagePort') {
        // 挂港信息
        state.options = res.content.map((item) => {
          return {
            id: item.id,
            value: item.id,
            label: item.berthPort,
            selectLabel: item.berthPort
          }
        })
      }
    })
    .finally(() => {
      state.loading = false
    })
}
// 获取options的基础数据
const getQueryData = (queryName) => {
  if (props.urlType == 'basedictdetail') {
    if (!props.urlQueryData) {
      throw new Error(`${props.urlType}必须需要urlQueryData`)
    } else {
      return {
        PageIndex: 1,
        PageSize: 50,
        Label: queryName,
        DictName: props.urlQueryData
      }
    }
  }
  if (props.urlType == 'crcontactcompany') {
    if (!props.urlQueryData) {
      throw new Error(`${props.urlType}必须需要urlQueryData`)
    } else {
      return {
        PageIndex: 1,
        PageSize: 50,
        code: queryName,
        businessCategory:
          props.urlQueryData == '委托单位' ? '' : props.urlQueryData
      }
    }
  } else if (props.urlType == 'port') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'CsPackageType') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'CsShip') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'CsVoyage') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'tradelane') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'csContainer') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'CsShipCompany') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  } else if (props.urlType == 'CsVoyagePort') {
    return {
      PageIndex: 1,
      PageSize: 50,
      KeyWords: queryName
    }
  }
}
/**
 * 返回选择的option
 * @param {object} data - 选择的option
 */
const handleOptionClick = (data) => {
  console.log(props.indexOfBox)
  // 箱子特有
  if (props.indexOfBox >= 0) {
    emit('getOption', data, props.indexOfBox)
  } else {
    emit('getOption', data)
  }
}
// 选择数据的变动，用于清除港口将AllOption对应的数据清空
const handleChange = (val) => {
  emit('handleChange', val)
}
watch(
  () => props.option,
  (newVal) => {
    state.options = newVal
  }
)

onMounted(() => {})
</script>

<style lang="scss" scoped></style>
